package cn.juque.systemservice.config;

import cn.juque.common.fastjson.serializer.FastJson2JsonRedisSerializer;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author nuoka
 */
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 配置第一个数据源的RedisTemplate 注意：这里指定使用名称=factory 的 RedisConnectionFactory 并且标识第一个数据源是默认数据源 @Primary
     *
     * @param redisConnectionFactory connection factory
     * @return RedisTemplate
     */
    @Bean("redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();

        //使用fastjson序列化
        FastJson2JsonRedisSerializer<?> fastJsonRedisSerializer = new FastJson2JsonRedisSerializer<>();
        // value值的序列化采用fastJsonRedisSerializer
        template.setValueSerializer(fastJsonRedisSerializer);
        template.setHashValueSerializer(fastJsonRedisSerializer);
        // key的序列化采用StringRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);

        return template;
    }
}
